package com.pansoft.openplanet.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.InputFilter;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.chat.activity.BaseActivity;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.http.OpenEthRequest;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.ToastUtil;
import com.efounder.utils.NumberTextWatcher;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.bean.AssetListBean;
import com.pansoft.openplanet.bean.WalletBean;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.fragment.BottomAssetChooseDialogFragment;
import com.pansoft.openplanet.fragment.BottomReceiveAddressChooseDialogFragment;
import com.pansoft.openplanet.fragment.BottomWalletChooseDialogFragment;
import com.pansoft.openplanet.util.BalanceUtil;
import com.pansoft.openplanet.util.DecimalDigitsInputFilter;
import com.pansoft.openplanet.util.EosNetParamUtil;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.pansoft.openplanet.util.UTXOTransactionManager;
import com.pansoft.openplanet.widget.BlockChainFeeSeekBar;
import com.pansoft.openplanet.widget.PassWordAlertDialog;
import com.utilcode.util.ToastUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.bitcoinj.core.Coin;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static android.app.DialogFragment.STYLE_NO_FRAME;

/**
 * 聊天页面的转账(eth btc)
 *
 * @author YQS
 */
public class ChatTransferActivity extends BaseActivity implements View.OnClickListener {


    private TextView tvTitle;
    private TextView tvReceiveWalletAddress;
    private LinearLayout llPay;
    private LinearLayout llAddress;
    private TextView tvBalance;
    private TextView tvPayAddress;
    private LinearLayout llTradeTypeLayout;
    private LinearLayout llAssetLayout;
    private TextView tvAssetBalance;
    private TextView tvAssetName;
    private LinearLayout llAmountLayout;
    private EditText etAmount;

////    原先的矿工费选择
//    private LinearLayout llExpense;
//    private TextView tvExpense;
//    private ImageView ivMinerFeeChoose;
//    private LinearLayout llSeekbar;
//    private TextView tvMin;
//    private SeekBar seekBar;
//    private TextView minerValue;
//    //    //原先的矿工费选择
//默认交易费用
//private String gas = "0.0004";

    private TextView tvNext;
    private LinearLayout llMoreAddress;//更多接收地址点击
    //eos相关
    private LinearLayout llReceiveAccountContainer;
    private LinearLayout llReceiveAccount;
    private TextView tvReceiveAccount;
    private LinearLayout llPayAccountContainer;
    private LinearLayout llPayAccount;
    private TextView tvPayAccount;

    //eos下改为钱包名
    private TextView tvReceive;
    private TextView tvPay;


    //聊天的人
    private String chatToUserId;

    //货币单位
    private String moneyUnit = "";
    private String assetUnit = "";
    //收款人钱包地址
    private String toWalletAddress;
    //链编号默认 eth
    private int chainId = IPAssetsConstant.CHAIN_ID_ETH;
    private IPAssetsConstant.ChainEnum chainEnum;
    //账户余额
    private String balance = "0";
    private String tokenBalance = "0";
    //钱包列表
    private List<WalletBean> walletBeans = new ArrayList<>();
    //对方接收钱包列表
    private List<WalletBean> receiveBeans = new ArrayList<>();
    //当前选中的自己的钱包
    private WalletBean currentSelfBean;
    private AssetListBean assetListBean;
    private AccountDao accountDao;
    private String[] items;//eos选择的账户

    private BlockChainFeeSeekBar blockFeeSekbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ipassets_activity_chat_transfer);
        EventBus.getDefault().register(this);
        accountDao = new AccountDao(this);
        initView();
        initIntentData();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (isFinishing()) {
            OpenEthRequest.cannelRequest();
        }
    }

    private void initView() {
        tvReceive = (TextView) findViewById(R.id.tv_receive);
        tvPay = (TextView) findViewById(R.id.tv_pay);

        llReceiveAccountContainer = (LinearLayout) findViewById(R.id.ll_receive_account_container);
        llReceiveAccount = (LinearLayout) findViewById(R.id.ll_receive_account);
        llReceiveAccount.setOnClickListener(this);
        tvReceiveAccount = (TextView) findViewById(R.id.tv_receive_account);
        llPayAccountContainer = (LinearLayout) findViewById(R.id.ll_pay_account_container);
        llPayAccount = (LinearLayout) findViewById(R.id.ll_pay_account);
        llPayAccount.setOnClickListener(this);
        tvPayAccount = (TextView) findViewById(R.id.tv_pay_account);

        tvReceiveWalletAddress = (TextView) findViewById(R.id.tv_receive_address);
        llPay = (LinearLayout) findViewById(R.id.ll_pay);
        llAddress = (LinearLayout) findViewById(R.id.ll_address);
        tvBalance = (TextView) findViewById(R.id.tv_balance);
        tvPayAddress = (TextView) findViewById(R.id.tv_pay_address);
        llTradeTypeLayout = (LinearLayout) findViewById(R.id.ll_trade_type_layout);
        llAssetLayout = (LinearLayout) findViewById(R.id.ll_asset_layout);
        tvAssetBalance = (TextView) findViewById(R.id.tv_asset_balance);
        tvAssetName = (TextView) findViewById(R.id.tv_asset_name);
        llAmountLayout = (LinearLayout) findViewById(R.id.ll_amount_layout);
        etAmount = (EditText) findViewById(R.id.et_amount);

        tvNext = (TextView) findViewById(R.id.tv_next);
        llMoreAddress = (LinearLayout) findViewById(R.id.ll_more_address);
        llMoreAddress.setOnClickListener(this);

        tvTitle = (TextView) findViewById(R.id.tv_title);
        llAddress.setOnClickListener(this);
        llAssetLayout.setOnClickListener(this);
        tvNext.setOnClickListener(this);

        blockFeeSekbar = (BlockChainFeeSeekBar) findViewById(R.id.block_fee_sekbar);


//        tvExpense.setOnClickListener(this);
//        llSeekbar.setVisibility(View.INVISIBLE);
//
//        ivMinerFeeChoose.setOnClickListener(this);
//        llExpense = (LinearLayout) findViewById(R.id.ll_expense);
//        tvExpense = (TextView) findViewById(R.id.tv_expense);
//        ivMinerFeeChoose = (ImageView) findViewById(R.id.iv_miner_fee_choose);
//        llSeekbar = (LinearLayout) findViewById(R.id.ll_seekbar);
//        tvMin = (TextView) findViewById(R.id.tv_min);
//        seekBar = (SeekBar) findViewById(R.id.seekBar);
//        minerValue = (TextView) findViewById(R.id.miner_value);
//
//        seekBar.setMax(56);
//        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
//            @Override
//            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//                gas = BalanceUtil.formatPrice(new BigDecimal((double) (progress + 4) / 10000)
//                                .doubleValue(),
//                        true, 4);
//                tvExpense.setText(gas + " " + moneyUnit);
//            }
//
//            @Override
//            public void onStartTrackingTouch(SeekBar seekBar) {
//
//            }
//
//            @Override
//            public void onStopTrackingTouch(SeekBar seekBar) {
//
//            }
//        });
        etAmount.addTextChangedListener(new NumberTextWatcher(etAmount));
    }

    private void initIntentData() {

        //transactionManager = new EthTokenTransactionManager(this);
        StubObject stubObject = (StubObject) getIntent().getSerializableExtra("stubObject");
        if (stubObject == null) {
            return;
        }
        String title = stubObject.getCaption();
        tvTitle.setText(title);

        chatToUserId = stubObject.getString("toUserId", "");
        String chainID = stubObject.getString("chainId", "1");
        chainId = Integer.valueOf(chainID);
        chainEnum = IPAssetsConstant.ChainEnum.getChainEnumByChainId(chainId);
        if (chainId == IPAssetsConstant.CHAIN_ID_EOS) {
            chainEnum = IPAssetsConstant.ChainEnum.getChainEnumByChainId(EosNetParamUtil.getEosChainId());
            llPayAccountContainer.setVisibility(View.VISIBLE);
            llReceiveAccountContainer.setVisibility(View.VISIBLE);
            tvPay.setText(ResStringUtil.getString(R.string.open_planet_receive_wallet));
            tvReceive.setText(ResStringUtil.getString(R.string.open_planet_pay_wallet));
            moneyUnit = EosNetParamUtil.getEosChainId() == IPAssetsConstant.CHAIN_ID_EOS ? "EOS" : "SYS";
        } else {
            //货币单位
            moneyUnit = chainEnum.chainName;
        }
        assetUnit = chainEnum.chainName;

        //获取对方地址
        getToAddressFromServer();
        if (chainId == IPAssetsConstant.CHAIN_ID_EOS) {
            etAmount.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(4)});
        } else {
            etAmount.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(8)});
        }

        if (chainId != IPAssetsConstant.CHAIN_ID_ETH) {
            //隐藏交易类型
            llTradeTypeLayout.setVisibility(View.GONE);
        }
        if (chainId == IPAssetsConstant.CHAIN_ID_BTC || chainId == IPAssetsConstant.CHAIN_ID_EOS ||
                chainId == IPAssetsConstant.CHAIN_ID_EOSTEST) {
            blockFeeSekbar.setVisibility(View.INVISIBLE);
        }

        blockFeeSekbar.setChainId(chainId);

        //加载本地钱包列表
        getLocalAccount(IPAssetsConstant.ChainEnum.getChainEnumByChainName(chainEnum.chainName));
        //设置数据
        refreshInterfaceData();
        getBalance();
    }

    private void getBalance() {
        //网络请求余额等信息
        if (currentSelfBean != null) {
            if (chainId == IPAssetsConstant.CHAIN_ID_BTC) {
                Account account = accountDao.getAccount(currentSelfBean.getAddress());
                UTXOTransactionManager.getBalance(TAG, account);
            } else if (chainId == IPAssetsConstant.CHAIN_ID_ETH) {
                requestAccountInfo(currentSelfBean.getAddress(), "", "");
            } else {
                //eos余额
                requestEosBalance(tvPayAccount.getText().toString());
            }
        }
    }

    //设置界面数据
    private void refreshInterfaceData() {
        if (currentSelfBean != null) {
            if (chainId == IPAssetsConstant.CHAIN_ID_EOS) {
                tvPayAddress.setText(currentSelfBean.getAccountName());
                tvPayAccount.setText(currentSelfBean.getAddress());
            } else {
                tvPayAddress.setText(currentSelfBean.getAddress());
            }
        }
        if (assetListBean != null) {
            assetUnit = assetListBean.getName();
            tvAssetBalance.setVisibility(View.VISIBLE);
        } else {
            assetUnit = chainEnum.chainName;
            tvAssetBalance.setVisibility(View.INVISIBLE);
        }

        tvAssetName.setText(assetUnit);
        tvBalance.setText(getString(R.string.open_planet_balance_with_unit, balance, moneyUnit));
        tvAssetBalance.setText(getString(R.string.open_planet_balance_with_unit, tokenBalance, assetUnit));
//        tvExpense.setText(gas + " " + moneyUnit);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBalanceUpdated(Coin coinBalance) {
        balance = coinBalance.toFriendlyString().replace("BTC", "");
        refreshInterfaceData();
    }

    /**
     * /**
     * 请求选择的代币余额
     *
     * @param curAddress
     * @param chainId
     */
    private void requestAccountInfo(final String curAddress, final String chainId,
                                    final String tokenId) {
        final HashMap<String, String> map = new HashMap<>();

        map.put("chainID", chainId);

        if (!"".equals(tokenId)) {
            map.put("tokenID", tokenId);
        } else {
            //todo 故意写一个错误的字段名
            map.put("tokenId", "3");
        }

        map.put("userAddress", curAddress);

        TCRequestUtil.getCommonRequest(TAG, "chain/getTokenInfo", map,
                new TCRequestUtil.TCRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        dismissLoading();

                        Log.i(TAG, response + "");
                        JSONObject jsonObject = JSONObject.fromObject(response);
                        //{"result":"success","AddressBalance":"0","TokenInfo":{"balance":"0","blockChainID":"2",
                        // "tokenAddress":"0xcb97e65f07da24d46bcdd078ebebd7c6e6e3d750","tokenDecimals":8,"tokenFullName":"Bytom",
                        // "tokenID":"10","tokenIcon":"http://cdn.openserver.cn/images/eth/tokens/btm.png","tokenName":"BTM"}}
                        if (jsonObject.getString("result").equals("success")) {

                            balance = jsonObject.optString("AddressBalance", "0");
                            if (!"0".equals(balance)) {
                                balance = BalanceUtil.formatPrice(Double.valueOf(balance), true, 8);
                            }
                            if (!tokenId.equals("") && !tokenId.equals("")) {
                                if (jsonObject.containsKey("TokenInfo")) {
                                    JSONObject tokenInfoObject = jsonObject.getJSONObject("TokenInfo");
                                    String assetBalance = tokenInfoObject.optString("balance", "0");

                                    tokenBalance = assetBalance;
                                    assetListBean = new AssetListBean.Builder().address(tokenInfoObject.optString("tokenAddress"))
                                            .balance(assetBalance)
                                            .id(tokenInfoObject.optString("tokenID"))
                                            .blockChainID(tokenInfoObject.optString("blockChainID"))
                                            .name(tokenInfoObject.optString("tokenName"))
                                            .icon(tokenInfoObject.optString("tokenIcon"))
                                            .tokenDecimals(tokenInfoObject.optInt("tokenDecimals"))
                                            .build();
                                }
                            }
                            refreshInterfaceData();
                        }
                    }

                    @Override
                    public void onFail(String error) {
                        dismissLoading();
                    }
                });
    }

    /**
     * 请求钱包余额
     *
     * @param address 钱包地址
     */
    private void requestEosBalance(String address) {
        HashMap<String, String> map = new HashMap<>();
        map.put("code", "eosio.token");
        map.put("accountName", address);
        map.put("chainId", String.valueOf(EosNetParamUtil.getEosChainId()));
        map.put("symbol", chainId == IPAssetsConstant.CHAIN_ID_EOS ? "EOS" : "SYS");
        TCRequestUtil.postCommonRequest(TAG, "eos/get_currency_balance", map, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    org.json.JSONObject jsonObject = new org.json.JSONObject(response);
                    if (jsonObject.optString("result").equals("success")) {
                        org.json.JSONArray dataArray = jsonObject.optJSONArray("data");
                        balance = dataArray.optString(0);
                        if (balance.equals("")) {
                            balance = "0.00";
                        } else {
                            balance = balance.replace(chainId == IPAssetsConstant.CHAIN_ID_EOS ?
                                    " EOS" : " SYS", "");
                        }
                        refreshInterfaceData();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(String error) {

            }
        });
    }

    /**
     * /**
     * 查询本地账户
     *
     * @param blockChainEnum ETH，BTC等
     */
    private void getLocalAccount(IPAssetsConstant.ChainEnum blockChainEnum) {
        walletBeans.clear();
        List<Account> accountList;
        if (chainId == IPAssetsConstant.CHAIN_ID_EOS) {
            accountList = accountDao.getAllActivatedEosAccount(blockChainEnum);
        } else {
            accountList = accountDao.getAllChildAccount(blockChainEnum);
        }
        if (accountList != null) {
            if (accountList.size() == 0) {
                if (chainId == IPAssetsConstant.CHAIN_ID_EOS) {
                    showExitAlert(getString(R.string.open_planet_no_local_wallet, "EOS"));
                } else {
                    showExitAlert(getString(R.string.open_planet_no_local_wallet, chainEnum.chainName));
                }
            }
            for (int i = 0; i < accountList.size(); i++) {
                Account account = accountList.get(i);

                if (account.getAccountType() == Account.ACCOUNT_TYPE_OBSERVE) {
                    //观察钱包不能转账
                    continue;
                }
                WalletBean walletBean = new WalletBean.Builder()
                        .accountName(account.getAcccountName())
                        .avatar(account.getAccountAvatar())
                        .address(account.getAddress())
                        .balance("0")
                        .build();
                if (account.isCurrentShow()) {
                    walletBean.setSelected(true);
                    currentSelfBean = walletBean;
                }
                walletBeans.add(walletBean);
            }
        }
        if (currentSelfBean == null && walletBeans.size() > 0) {
            currentSelfBean = walletBeans.get(0);
            currentSelfBean.setSelected(true);
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (view.getId() == R.id.tv_next) {
            //下一步
            String inputAmount = etAmount.getText().toString();
            if (inputAmount.equals("")) {
                ToastUtils.showShort(R.string.open_planet_input_transfer_amount);
                return;
            }
            if (tvReceiveWalletAddress.getText().toString().equals("")) {
                ToastUtils.showShort(R.string.open_planet_receive_address_not_null);
                return;
            }
            if (tvPayAddress.getText().toString().equals("")) {
                ToastUtils.showShort(R.string.open_planet_select_pay_address);
                return;
            }
            //开始转账
            verificationPwd();

        } else if (view.getId() == R.id.tv_expense || id == R.id.iv_miner_fee_choose) {
            //选择矿工费用
//            if (llSeekbar.getVisibility() == View.VISIBLE) {
//                llSeekbar.setVisibility(View.INVISIBLE);
//            } else {
//                llSeekbar.setVisibility(View.VISIBLE);
//            }

        } else if (view.getId() == R.id.ll_address) {
            //选择钱包
            showWalletChoose();
        } else if (view.getId() == R.id.ll_asset_layout) {
            //交易类型
            showTokenSelect();
        } else if (view.getId() == R.id.ll_more_address) {
            //选择更多接收地址
            if (chainId != IPAssetsConstant.CHAIN_ID_ETH) {
                showMoreReceiveAddress(receiveBeans);
            }
        } else if (view.getId() == R.id.ll_receive_account) {
            changeAccountAlert(true, tvReceiveWalletAddress.getText().toString());
        } else if (view.getId() == R.id.ll_pay_account) {
            changeAccountAlert(false, tvPayAccount.getText().toString());
        }
    }


    /**
     * 切换钱包
     */
    private void showWalletChoose() {

        BottomWalletChooseDialogFragment bottomWalletChooseDialogFragment = new
                BottomWalletChooseDialogFragment();
        bottomWalletChooseDialogFragment.setData(this, walletBeans, chainEnum.chainId);
        bottomWalletChooseDialogFragment.setStyle(STYLE_NO_FRAME, 0);
        bottomWalletChooseDialogFragment.hideBalace(true);
        bottomWalletChooseDialogFragment.show(getSupportFragmentManager(), "WalletChoose");
        bottomWalletChooseDialogFragment.setOnWalletSelectChangedListener(new BottomWalletChooseDialogFragment.OnWalletSelectChangedListener() {
            @Override
            public void onWalletChanged(WalletBean walletBean) {
                currentSelfBean = walletBean;
                balance = currentSelfBean.getBalance();
                //本地数据刷新界面
                refreshInterfaceData();
                //获取余额
                getBalance();
                //服务器刷新界面
//                requestAccountInfo(currentSelfBean.getAddress(),
//                        chainEnum.chainId + "", assetListBean == null ? "" : assetListBean.getId());
            }
        });
    }

    /**
     * 选择账户,eos
     *
     * @param toAddress 是否是收款地址
     * @param address   地址
     */
    private void changeAccountAlert(final boolean toAddress, String address) {
        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(this);
        int checkedItem = 0;
        if (toAddress) {
            for (WalletBean walletBean : receiveBeans) {
                if (address.equals(walletBean.getAccountName())) {
                    if (walletBean.getEosAccountNames() == null || walletBean.getEosAccountNames().equals("")) {
                        items = new String[]{walletBean.getAddress()};
                    } else {
                        items = walletBean.getEosAccountNames().split("_");

                        for (int i = 0; i < items.length; i++) {
                            if (walletBean.getAddress().equals(items[i])) {
                                checkedItem = i;
                            }
                        }
                    }
                }
            }
        } else {
            Account account = accountDao.getAccount(address);
            if (account.getEosAccountNames() == null || account.getEosAccountNames().equals("")) {
                items = new String[]{account.getAddress()};
            } else {
                items = account.getEosAccountNames().split("_");

                for (int i = 0; i < items.length; i++) {
                    if (account.getAddress().equals(items[i])) {
                        checkedItem = i;
                    }
                }
            }
        }

        builder
                .setTitle(ResStringUtil.getString(R.string.open_planet_choose_account))
                .setSingleChoiceItems(items, checkedItem, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (toAddress) {
                            toWalletAddress = items[i];
                            tvReceiveAccount.setText(toWalletAddress);
                        } else {
                            tvPayAccount.setText(items[i]);
                            getBalance();
                        }
                        dialogInterface.dismiss();
                    }
                })
                .setNegativeButton(R.string.common_text_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .setCancelable(false);
        androidx.appcompat.app.AlertDialog dialog = builder.create();
        dialog.show();
    }

    /**
     * 切换代币
     */
    private void showTokenSelect() {
        if (currentSelfBean == null) {
            return;
        }
        BottomAssetChooseDialogFragment bottomAssetChooseDialogFragment = new
                BottomAssetChooseDialogFragment();
        bottomAssetChooseDialogFragment.setData(this, currentSelfBean.getAddress(),
                assetListBean == null ? "" : assetListBean.getName());
        bottomAssetChooseDialogFragment.setStyle(STYLE_NO_FRAME, 0);
        bottomAssetChooseDialogFragment.show(getSupportFragmentManager(), "WalletChoose");
        bottomAssetChooseDialogFragment.setOnAssetSelectChangedListener(new BottomAssetChooseDialogFragment.OnAssetSelectChangedListener() {
            @Override
            public void onAssetChanged(AssetListBean assetListBean1) {
                assetListBean = assetListBean1;
                String tokenId = "";
                if (assetListBean1.getName().equals("ETH")) {
                    assetListBean = null;
                } else {
                    tokenId = assetListBean.getId();
                }
                refreshInterfaceData();

                requestAccountInfo(currentSelfBean.getAddress(), chainId + "", tokenId);
            }
        });
    }

    private void showMoreReceiveAddress(List<WalletBean> walletBeanList) {
        BottomReceiveAddressChooseDialogFragment bottomWalletChooseDialogFragment = new
                BottomReceiveAddressChooseDialogFragment();
        bottomWalletChooseDialogFragment.setData(this, walletBeanList, chainEnum.chainId);
        bottomWalletChooseDialogFragment.setStyle(STYLE_NO_FRAME, 0);
        bottomWalletChooseDialogFragment.show(getSupportFragmentManager(), "ReceiveAddressChoose");
        bottomWalletChooseDialogFragment.setOnWalletSelectChangedListener(new BottomReceiveAddressChooseDialogFragment.OnWalletSelectChangedListener() {
            @Override
            public void onWalletChanged(WalletBean walletBean) {
                toWalletAddress = walletBean.getAddress();
                if (chainId == IPAssetsConstant.CHAIN_ID_EOS) {
                    tvReceiveWalletAddress.setText(walletBean.getAccountName());
                    tvReceiveAccount.setText(toWalletAddress);
                } else {
                    tvReceiveWalletAddress.setText(toWalletAddress);
                }
            }
        });
    }

    private void getToBtcAddress(String mainAddress) {
        final HashMap<String, String> map = new HashMap<>();
        map.put("mainAccountAddress", mainAddress);
        TCRequestUtil.getCommonRequest(TAG, "account/getAllWallet", map,
                new TCRequestUtil.TCRequestCallback() {
                    @Override
                    public void onSuccess(String response) {

                        Log.i(TAG, response + "");
                        try {
                            JSONObject jsonObject = JSONObject.fromObject(response);
                            if (jsonObject.optString("result", "").equals("success")) {
                                JSONArray jsonArray = jsonObject.optJSONArray("ChildrenWallet");
                                if (jsonArray != null && jsonArray.size() > 0) {
                                    for (int i = 0; i < jsonArray.size(); i++) {
                                        WalletBean walletBean = new WalletBean();
                                        JSONObject jsonObject1 = jsonArray.optJSONObject(i);
                                        if (jsonObject1.optString("blockChainName").equals("BTC")) {
                                            walletBean.setAddress(jsonObject1.optString("accountAddress", ""));
                                            walletBean.setAccountName(jsonObject1.optString("accountName"));
                                            walletBean.setAvatar(jsonObject1.optString("accountIcon"));
                                            receiveBeans.add(walletBean);
                                        }
                                    }
                                    toWalletAddress = receiveBeans.get(0).getAddress();
                                    tvReceiveWalletAddress.setText(toWalletAddress);
                                } else {
                                    showExitAlert(getString(R.string.open_planet_the_other_no_wallet, "BTC"));
                                }
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            showExitAlert(getString(R.string.open_planet_the_other_no_wallet, "BTC"));
                        }
                    }

                    @Override
                    public void onFail(String error) {
                    }
                });
    }

    /**
     * 获取对方eos地址
     *
     * @param mainAddress 主账户地址
     */
    private void getToEosAddress(String mainAddress) {
        final HashMap<String, String> map = new HashMap<>();
        map.put("mainAccountAddress", mainAddress);
        TCRequestUtil.getCommonRequest(TAG, "account/getAllWallet", map,
                new TCRequestUtil.TCRequestCallback() {
                    @Override
                    public void onSuccess(String response) {

                        Log.i(TAG, response + "");
                        try {
                            JSONObject jsonObject = JSONObject.fromObject(response);
                            if (jsonObject.optString("result", "").equals("success")) {
                                JSONArray jsonArray = jsonObject.optJSONArray("ChildrenWallet");
                                if (jsonArray != null && jsonArray.size() > 0) {
                                    for (int i = 0; i < jsonArray.size(); i++) {
                                        WalletBean walletBean = new WalletBean();
                                        JSONObject jsonObject1 = jsonArray.optJSONObject(i);
                                        if (jsonObject1.optString("blockChainName").equals(EosNetParamUtil.getEosChainName())) {
                                            walletBean.setAddress(jsonObject1.optString("accountAddress", ""));
                                            walletBean.setAccountName(jsonObject1.optString("accountName"));
                                            walletBean.setEosAccountNames(jsonObject1.optString("eosAccountNames"));
                                            walletBean.setAvatar(jsonObject1.optString("accountIcon"));
                                            if (jsonObject1.optInt("eosIsActive") == 1) {
                                                receiveBeans.add(walletBean);
                                            }
                                        }
                                    }
                                    String toWalletName = receiveBeans.get(0).getAccountName();
                                    toWalletAddress = receiveBeans.get(0).getAddress();
                                    tvReceiveWalletAddress.setText(toWalletName);
                                    tvReceiveAccount.setText(toWalletAddress);
                                } else {
                                    showExitAlert(getString(R.string.open_planet_the_other_no_wallet, "EOS"));
                                }
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            showExitAlert(getString(R.string.open_planet_the_other_no_wallet, "EOS"));
                        }
                    }

                    @Override
                    public void onFail(String error) {
                    }
                });
    }

    private void showExitAlert(String message) {
        if (isFinishing() || isDestroyed()) {
            return;
        }
        new AlertDialog.Builder(ChatTransferActivity.this).setMessage(message).setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        }).setCancelable(false).show();
    }

    /**
     * 获取对方主钱包地址（现在只支持eth）
     */
    private void getToAddressFromServer() {
        final User currentUser = WeChatDBManager.getInstance().getOneUserById(Integer.valueOf(chatToUserId));
        OpenEthRequest.getUserEthByImUserId(this, Integer.valueOf(chatToUserId), new OpenEthRequest.EthRequestListener() {
            @Override
            public void onSuccess(String ethAddress, String publicKey1, String RSAPublicKey1) {
                currentUser.setWalletAddress(ethAddress);
                toWalletAddress = ethAddress;
                if (chainId == IPAssetsConstant.CHAIN_ID_BTC) {
                    getToBtcAddress(toWalletAddress);
                } else if (chainId == IPAssetsConstant.CHAIN_ID_ETH) {
                    tvReceiveWalletAddress.setText(toWalletAddress);
                } else {
                    //eos地址
                    getToEosAddress(toWalletAddress);
                }
            }

            @Override
            public void onFail(String error) {
                toWalletAddress = currentUser.getWalletAddress();
                if (toWalletAddress == null || toWalletAddress.equals("")) {
                    showExitAlert(ResStringUtil.getString(R.string.open_planet_get_main_address_fail));
                    return;
                }
                if (chainId == IPAssetsConstant.CHAIN_ID_BTC) {
                    getToBtcAddress(toWalletAddress);
                } else if (chainId == IPAssetsConstant.CHAIN_ID_ETH) {
                    tvReceiveWalletAddress.setText(toWalletAddress);
                } else {
                    getToEosAddress(toWalletAddress);
                }
            }
        });

    }

    //开始转账
    private void verificationPwd() {
        PassWordAlertDialog dialog = new PassWordAlertDialog(this, new PassWordAlertDialog.OnEnterClick() {
            @Override
            public void passVerifySuccess(String passWord) {
                //TCLoadingDataView.show(ChatTransferActivity.this, "交易中...");
//                if (chainId == IPAssetsConstant.CHAIN_ID_ETH) {
                startTransfer();
//                } else if (chainId == IPAssetsConstant.CHAIN_ID_BTC) {
//                    startBtcTransfer();
//                }

            }
        });
        dialog.show();
    }

    //开始转账
    private void startTransfer() {
        final String receiveAddress = tvReceiveWalletAddress.getText().toString();
        final String payAddress = tvPayAddress.getText().toString();//
        // final String contractAddress = assetListBean == null ? "" : assetListBean.getAddress();
        final String amount = etAmount.getText().toString();

        final String gasPrice1 = blockFeeSekbar.getProgressGas();
        final String convertGas = blockFeeSekbar.getGasConversion();

        final Account account = accountDao.getAccount(currentSelfBean.getAddress());
        if (account != null) {

            if (chainId == IPAssetsConstant.CHAIN_ID_EOS) {
                ChatTransferSuccessActivity.start(this, tvReceiveAccount.getText().toString(),
                        tvPayAccount.getText().toString(), amount, gasPrice1, convertGas, EosNetParamUtil.getEosChainId(),
                        assetListBean, chatToUserId, account.getAccountType());
            } else {
                ChatTransferSuccessActivity.start(this, receiveAddress, payAddress, amount, gasPrice1, convertGas,
                        chainId, assetListBean, chatToUserId, account.getAccountType());
            }
            finish();
        } else {
            showTransactionResult(false, ResStringUtil.getString(R.string.open_planet_transfer_fail));
        }

    }

    private void showTransactionResult(boolean isSuccess, String result) {
        //  TCLoadingDataView.dismiss();
        ToastUtil.showToast(this, result + "  " + isSuccess);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
